<template>
  <div class="information-container">
    <!-- 用户信息卡片 -->
    <el-card class="user-card">
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
          <el-button
            type="primary"
            size="small"
            @click="openEditDialog"
          >
            编辑资料
          </el-button>
        </div>
      </template>

      <div class="user-profile">
        <!-- 头像区 -->
        <div class="avatar-section">
          <el-avatar :size="120" :src="userInfo.avatar || defaultAvatar" />
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :http-request="customUpload"
          >
            <el-button type="text" icon="el-icon-camera">更换头像</el-button>
          </el-upload>
        </div>

        <!-- 信息区 -->
        <div class="info-section">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="用户名">
              {{ userInfo.username || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="邮箱">
              {{ userInfo.email || '未绑定' }}
            </el-descriptions-item>
            <el-descriptions-item label="性别">
              {{ userInfo.gender || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="用户类型">
              {{ userInfo.sign === 1 ? '店长' : '普通用户' }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-card>

    <!-- 其他信息区域 -->
    <el-card class="additional-info">
      <el-tabs v-model="activeTab" type="border-card">
        <el-tab-pane label="订单历史" name="orders">
          <OrderHistory />
        </el-tab-pane>
        <el-tab-pane label="收藏店铺" name="favorites">
          <FavoriteShops />
        </el-tab-pane>
        <el-tab-pane label="安全设置" name="security">
          <SecuritySettings />
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 编辑用户信息对话框 -->
    <el-dialog
      title="编辑个人信息"
      :visible.sync="showEditDialog"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="editRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="editForm.gender" placeholder="请选择性别" style="width: 100%">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input
            v-model="editForm.password"
            type="password"
            placeholder="不修改请留空"
            show-password
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button
          type="primary"
          :loading="submitting"
          @click="submitEdit"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { updateUser, uploadAvatarLocal, updateAvatar } from '@/api/user'
import { mapGetters } from 'vuex'
import defaultAvatar from '@/assets/default-avatar.png'
import OrderHistory from './components/OrderHistory.vue'
import FavoriteShops from './components/FavoriteShops.vue'
import SecuritySettings from './components/SecuritySettings.vue'

export default {
  name: 'Information',
  components: {
    OrderHistory,
    FavoriteShops,
    SecuritySettings
  },
  data() {
    return {
      activeTab: 'orders',
      showEditDialog: false,
      submitting: false,
      editForm: {
        userid: null,
        username: '',
        email: '',
        gender: '',
        password: ''
      },
      editRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['isLoggedIn', 'userInfo']),
    
    uploadUrl() {
      return '/ele/user/uploadAvatar'
    }
  },
  methods: {
    // 自定义上传方法
    customUpload(options) {
      const formData = new FormData()
      formData.append('file', options.file)
      
      uploadAvatarLocal(formData)
        .then(response => {
          if (response.code === 20000) {
            // 上传成功后，更新数据库中的头像字段
            return updateAvatar(this.userInfo.userid, response.data)
          } else {
            throw new Error(response.msg || '头像上传失败')
          }
        })
        .then(updateResponse => {
          if (updateResponse.code === 20000) {
            // 更新store中的用户信息
            this.$store.commit('user/SET_USER_INFO', {
              ...this.userInfo,
              avatar: this.userInfo.avatar
            })
            this.$message.success('头像更新成功')
            options.onSuccess(updateResponse)
          } else {
            throw new Error(updateResponse.msg || '头像更新失败')
          }
        })
        .catch(error => {
          this.$message.error('头像上传失败：' + (error.message || '未知错误'))
          options.onError(error)
        })
    },
    
    handleAvatarSuccess(response) {
      // 这个方法现在不会被调用，因为我们使用了自定义上传
      console.log('Avatar upload success:', response)
    },
    
    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('只能上传图片文件!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('头像图片大小不能超过 2MB!')
        return false
      }
      return true
    },
    
    openEditDialog() {
      this.editForm = {
        userid: this.userInfo.userid,
        username: this.userInfo.username || '',
        email: this.userInfo.email || '',
        gender: this.userInfo.gender || '',
        password: ''
      }
      this.showEditDialog = true
    },
    
    submitEdit() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.submitting = true
          
          // 如果没有输入新密码，则不更新密码
          const submitData = { ...this.editForm }
          if (!submitData.password) {
            delete submitData.password
          }
          
          updateUser(submitData)
            .then(() => {
              this.$message.success('更新成功')
              
              // 更新store中的用户信息
              this.$store.commit('user/SET_USER_INFO', {
                ...this.userInfo,
                ...submitData
              })
              
              this.showEditDialog = false
            })
            .catch((error) => {
              this.$message.error('更新失败：' + (error.message || '未知错误'))
            })
            .finally(() => {
              this.submitting = false
            })
        }
      })
    }
  },
  
  mounted() {
    if (!this.isLoggedIn) {
      this.$message.warning('请先登录')
      this.$router.push('/login')
    }
  }
}
</script>

<style lang="scss" scoped>
.information-container {
  max-width: 1000px;
  margin: 20px auto;
  padding: 0 20px;

  .user-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 18px;
      font-weight: bold;
    }

    .user-profile {
      display: flex;
      padding: 20px;

      .avatar-section {
        width: 200px;
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-right: 30px;

        .avatar-uploader {
          margin-top: 15px;
          text-align: center;
        }
      }

      .info-section {
        flex: 1;
      }
    }
  }

  .additional-info {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .information-container {
    padding: 0 10px;

    .user-profile {
      flex-direction: column !important;

      .avatar-section {
        width: 100% !important;
        margin-right: 0 !important;
        margin-bottom: 20px;
      }
    }
  }
}
</style>


